;
(function() {
  if (window.Vue) {
    var rate = 3;
    var drawInput = function(ctx, x, y, w, h, focus, word, fontSize) {
      x = x * rate;
      y = y * rate;
      w = w * rate;
      h = h * rate;
      fontSize = fontSize * rate;
      ctx.lineJoin = "round";
      ctx.lineWidth = 2;
      ctx.fillStyle = "rgba(0,0,0,0)";
      ctx.shadowBlur = 1;
      ctx.strokeStyle = focus ? "#00a4f5" : '#ccc';
      ctx.shadowColor = ctx.strokeStyle;
      ctx.strokeRect(x + 5, y + 5, w - 10, h - 10);
      if (word) {
        ctx.shadowBlur = 0;
        ctx.strokeStyle = "rgba(0,0,0,0)";
        ctx.shadowColor = 'none';
        ctx.fillStyle = focus ? "#00a4f5" : '#000';
        ctx.font = "normal normal 100 " + fontSize + "px Helvetica";
        ctx.fillText(word, x + (w - 0.6 * fontSize) / 2, y + (h + 0.65 * fontSize) / 2);
      }
    };
    // 设置光标位置
    function setCaretPosition(textDom, pos) {
      if (textDom.setSelectionRange) {
        // IE Support
        textDom.focus();
        textDom.setSelectionRange(pos, pos);
      } else if (textDom.createTextRange) {
        // Firefox support
        var range = textDom.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
      }
    }
    var cursor = document.createElement('div');
    cursor.style.cssText = 'position:absolute;z-index:2';
    var count = 0;
    var opacitys = [1, 0.8, 0.5, 0.2, 0, 0, 0.4, 0.8, 1];
    var max = opacitys.length;
    setInterval(function() {
      count = count % max;
      cursor.style.opacity = opacitys[count];
      count++;
    }, 1000 / 10)
    var drawCursor = function(cursor, x, y, w, h, focus, word, fontSize) {
      cursor.style.background = '#00a4f5';
      cursor.style.width = fontSize / 9 + 'px';
      cursor.style.height = fontSize + 'px';
      cursor.style.left = x + (w - fontSize / 9) / 2 + (word ? 0.5 * fontSize : 0) + 'px';
      cursor.style.top = y + (h - fontSize) / 2 + 'px';
      return cursor;
    }

    Vue.component('x-words', {
      render: function(h) {
        var self = this;
        var canvas = h('canvas', {
          style: {
            position: 'absolute',
            top: 0,
            left: 0,
            height: '100%',
            width: '100%',
            background: 'rgba(0,0,0,0)'
          }
        });
        var input = h('input', {
          domProps: {
            value: this.value
          },
          on: {
            input: function(e) {
              e.target.value = self.setCode(e.target.value);
            },
            focus: function() {
              self.focus = true;
            },
            blur: function() {
              self.focus = false;
            }
          },
          style: {
            border: 'none',
            backgroundColor: 'rgba(0,0,0,0)',
            color: 'rgba(0,0,0,0)',
            '-webkit-box-sizing': 'border-box',
            boxSizing: 'border-box',
            '-webkit-tap-highlight-color': 'transparent',
            outline: 'none',
            display: 'block',
            height: '1px',
            width: '1px',
            lineHeight: '1px',
            top: '-50px',
            left: '-50px',
            position: 'absolute'
          },
          domProps: {
            type: this.type,
            autofocus: this.autofocus,
            maxlength: this.size
          }
        });
        return h('label', {
          style: {
            position: 'relative',
            overflow: 'hidden'
          }
        }, [canvas, input]);
      },
      props: {
        size: {
          type: Number,
          default: 6
        },
        value: {
          type: String,
          default: ''
        },
        validate: {
          type: [Function, RegExp],
          default: function(word) {
            return /\d/.test(word);
          }
        },
        type: {
          type: String,
          default: 'number'
        },
        drawInput: {
          type: Function,
          default: drawInput
        },
        drawCursor: {
          type: Function,
          default: drawCursor
        },
        autofocus: {
          type: Boolean,
          default: true
        }
      },
      data: function() {
        return {
          focus: false
        }
      },
      computed: {
        index: function() {
          return this.value.length;
        }
      },
      watch: {
        index: function(i) {
          if (i == this.size) {
            this.$emit('full', this.value);
            this.draw(this.$el, this.size, this.index, this.value, this.focus);
          }
        },
        focus: function() {
          this.draw(this.$el, this.size, this.index, this.value, this.focus);
        },
        value: function() {
          this.draw(this.$el, this.size, this.index, this.value, this.focus);
        }
      },
      mounted: function() {
        if (this.autofocus) {
          this.$el.focus();
          canvas = this.$el.children[0];
          ctx = canvas.getContext('2d');
          this.draw(this.$el, this.size, this.index, this.value, this.focus)
        }
      },
      methods: {
        setCode: function(value) {
          var matched,
            code = '';
          if (value) {
            if (matched = value.match(/\d/g)) {
              code = matched.join('').substr(0, 6);
            }
          }
          this.$emit('input', code);
          return code;
        },
        test: function(word) {
          return typeof this.validate == 'function' ? this.validate(word) : this.validate.test(word);
        },
        getCells: function($el, len, index, code, _focus) {
          if (!$el) {
            return;
          }
          var cells = [],
            x,
            focus,
            i = 0;
          width = $el.offsetWidth,
          height = $el.offsetHeight,
          space = (width - height * len) / (len - 1),
          fontSize = getComputedStyle($el, false)['font-size'];
          fontSize = fontSize.substring(0, fontSize.length - 2) * 1;
          for (; i < len; i++) {
            x = (space + height) * i;
            focus = _focus ? index == i || ((i == len - 1) && (index == len)) : false;
            cells.push([
              x,
              0,
              height,
              height,
              focus,
              code[i],
              fontSize
            ]);
          }
          return cells;
        },
        draw: function($el, len, index, code, focus) {
          var cells = this.getCells($el, len, index, code, focus);
          if (cells) {
            if (!focus && (cursor.parentNode == $el)) {
              $el.removeChild(cursor);
            } else if (cursor.parent != $el) {
              $el.appendChild(cursor);
            }
            var i = 0;
            canvas.width = $el.offsetWidth * rate;
            canvas.height = $el.offsetHeight * rate;
            for (; i < len; i++) {
              if (cells[i][4]) this.drawCursor.apply(this, [cursor].concat(cells[i]));
              this.drawInput.apply(this, [ctx].concat(cells[i]));
            }
          }
        }
      }
    });
  }
})();
